package com.agile.leetcode.string.builderAndBuffer;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * StringBuilder 线程不安全，当多个线程进行时，会导致累加的长度和预想的不一致
 * StringBuffer 线程安全
 * @Author:ChenZhangKun
 * @Date: 2021/3/24 16:51
 */
public class BuilderAndBufferDemo {
    // 定义
    // 线程不安全的builder
    private StringBuilder builder = new StringBuilder();
    // 线程安全的buffer
    private StringBuffer buffer = new StringBuffer();

    public static void main(String[] args) throws InterruptedException {
        BuilderAndBufferDemo demo = new BuilderAndBufferDemo();
        new Thread(() -> {
            System.out.println(demo.getStr());
        }).start();
        new Thread(() -> {
            System.out.println(demo.getStr());
        }).start();
        TimeUnit.SECONDS.sleep(2);
        // 分别新开两个线程来进行演示
        new Thread(() -> {
            System.out.println(demo.getStr_1());
        }).start();
        new Thread(() -> {
            System.out.println(demo.getStr_1());
        }).start();
    }

    public String getStr() {
        String[] arr = new String[]{"A", "F", "G", "H"};
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            int j = random.nextInt(4);
            String s = arr[j];
            builder.append(s);
        }
        return builder.toString();
    }

    public String getStr_1() {
        String[] arr = new String[]{"A", "F", "G", "H"};
        Random random = new Random();
        for (int i = 0; i < arr.length; i++) {
            int j = random.nextInt(arr.length);
            String s = arr[j];
            buffer.append(s);
        }
        return buffer.toString();
    }
}
